﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataSystem;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Data.SqlClient;

namespace GoogleProvider
{
    public class Google : IDataProvider
    {
        #region IDataProvider Members

        public void SetConnection(string connectionsString)
        {

        }

        public List<Dictionary<string, object>> GetWeather(string search)
        {
            try
            {
                // http://www.google.com/ig/api?weather=82072
                WebRequest wbr = WebRequest.Create("http://www.google.com/ig/api?weather=" + search);
                Stream wbresp = wbr.GetResponse().GetResponseStream();
                StreamReader str = new StreamReader(wbresp);
                string content = str.ReadToEnd();
                str.Close();

                XElement weatherEle = XElement.Parse(content);

                List<Dictionary<string, object>> outobj = new List<Dictionary<string, object>>();

                foreach (var subele in weatherEle.Descendants().First().Elements())
                {
                    Dictionary<string, object> row = new Dictionary<string, object>();
                    row.Add("rowdesc", subele.Name);
                    foreach (var col in subele.Elements())
                    {
                        row.Add(col.Name.ToString(), col.Attribute("data").Value);

                    }



                    outobj.Add(row);
                }
                return outobj;
            }
            catch { return null; }
        }

        public List<Dictionary<string, object>> GetData(string sql)
        {
            SQLParser parser = new SQLParser(sql);
            if (parser.Action == SQLParser.SQLAction.SELECT && parser.ObjectName == "weather")
            {
                var query = parser.GetWhereParamByColumn("query");
                if (query != null) return GetWeather(query);
                                
            }
            return null;
        }

        public List<Dictionary<string, object>> GetData(string connectionsString, string sql)
        {
            return GetData(sql);
        }

        #endregion
    }
}
